import { fetchNoticeList, fetchReadMsg, fetchReadAllMsg } from '@/services/message';
import { message } from 'antd';

export default {
    namespace: 'userMessage',
    state: {
        allNoticeData: {
            rows: [],
            total: 0
        },
        readNoticeData: {
            rows: [],
            total: 0
        },
        unreadNoticeData: {
            rows: [],
            total: 0
        },
        total: 0,
        unReadStateCount: 0
    },

    effects: {
        *getNoticeList({ payload, callback }, { call, put }) {
            const result = yield call(fetchNoticeList, payload);
            const { code, data, msg } = result;
            if (code === 10000) {
                const { page = {}, unReadStateCount, total } = data || {};
                let tempObj = {};
                if (payload.readState === -1) {
                    tempObj = {
                        allNoticeData: {
                            ...page
                        }
                    };
                }

                if (payload.readState === 0) {
                    tempObj = {
                        unreadNoticeData: {
                            ...page
                        }
                    };
                }

                if (payload.readState === 1) {
                    tempObj = {
                        readNoticeData: {
                            ...page
                        }
                    };
                }

                yield put({
                    type: 'save',
                    payload: {
                        ...tempObj,
                        total,
                        unReadStateCount
                    }
                });

                if (callback) {
                    callback();
                }
            } else {
                // 查找不到user就不弹出提示
                const isLogin = window.localStorage.getItem('user');
                if (isLogin) {
                    message.error(msg);
                }
            }
        },
        *setMarkAsRead({ payload, callback }, { call }) {
            const result = yield call(fetchReadMsg, payload);
            const { code, msg } = result;
            if (code === 10000) {
                if (callback) {
                    callback(msg);
                }
            } else {
                message.error(msg);
            }
        },
        *setMarkAllAsRead({ callback }, { call }) {
            const result = yield call(fetchReadAllMsg);
            const { code, msg } = result;
            if (code === 10000) {
                message.success(msg);
                if (callback) {
                    callback();
                }
            } else {
                message.error(msg);
            }
        }
    },

    reducers: {
        save(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        }
    }
};
